package com.youaishujuhui.devops.web.service;

import java.util.HashMap;
import java.util.Map;

import org.nutz.http.Http;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.hutool.core.text.UnicodeUtil;

@Service
public class DnsService {
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	private static final String CREATE_RECORD_URL = "https://dnsapi.cn/Record.Create";
	
	@Autowired
	private PropertiesService propertiesService;

	public String createRecord(String domain, String subDomain, String recordLine, String value) throws Exception {
		Map<String, Object> parms = new HashMap<String, Object>();
		
		// 公共参数		
	    parms.put("login_token", propertiesService.getDnspodToken());
	    parms.put("format", "json");
	    parms.put("lang", "cn");
	    parms.put("error_on_empty", "no");
	    
	    // domain_id 或 domain, 分别对应域名ID和域名, 提交其中一个即可
	    parms.put("domain", domain);
	    
	    // 主机记录, 如 www，可选，如果不传，默认为 @
	    parms.put("sub_domain", subDomain);
	    
	    // 记录类型，通过API记录类型获得，大写英文，比如：A, 必选
	    parms.put("record_type", "A");
	    
	    // 记录线路，通过API记录线路获得，中文，比如：默认
	    parms.put("record_line", recordLine);
	    
	    // 记录值, 如 IP:200.200.200.200, CNAME: cname.dnspod.com., MX: mail.dnspod.com., 必选
	    parms.put("value", value);
	    
	    String response = Http.post(CREATE_RECORD_URL,
	                                parms,
	                                5 * 1000); // 可以同时设置超时时间
	    
	    response = UnicodeUtil.toString(response);
	    
	    logger.info("dnspod:" + response);

		return response;
	}
	
}
